package com.yifeng.repo.base.utils.runtime;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by daibing on 2019/11/15.
 */
public class CmdHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(CmdHelper.class);

    public static String exec(String cmd) {
        return exec(cmd, false);
    }

    /**
     * 针对自带交互提示符的命令需要关闭标准输入，比如：wmic
     */
    public static String exec(String cmd, boolean closeOutputStream) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd, null);
            if (closeOutputStream) {
                process.getOutputStream().close();
            }
            int exit = process.waitFor();
            String result = doRead(process.getInputStream());
            if (isEmptyText(result)) {
                result = doRead(process.getErrorStream());
            }
            LOGGER.info("exec success: cmd={}, exit={}, result={}", cmd, exit, result);
            return result;
        } catch (Exception e) {
            if (process != null) {
                LOGGER.error("exec failed: info={}, error={}", doRead(process.getInputStream()), doRead(process.getErrorStream()));
            }
            LOGGER.error("exec exception: e=", e);
            throw new RuntimeException(e);
        } finally {
            try {
                if (process != null) {
                    process.getInputStream().close();
                    process.getErrorStream().close();
                    process.destroy();
                }
            } catch (IOException e) {
                LOGGER.info("exec finally exception: e=", e);
            }
        }
    }

    public static void asyncExec(String cmd) {
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(cmd, null);
            LOGGER.info("asyncExec success: cmd={}", cmd);
        } catch (Exception e) {
            if (process != null) {
                LOGGER.error("asyncExec failed: info={}, error={}", doRead(process.getInputStream()), doRead(process.getErrorStream()));
            }
            LOGGER.error("asyncExec exception: e=", e);
            throw new RuntimeException(e);
        }
    }

    private static String doRead(InputStream is) {
        try {
            byte[] buf2 = new byte[1024];
            ByteArrayOutputStream baos = new ByteArrayOutputStream(4 * 1024);
            for (int num; (num = is.read(buf2)) != -1; ) {
                baos.write(buf2, 0, num);
            }
            return baos.toString("GBK");
        } catch (IOException e) {
            return null;
        }
    }

    private static boolean isEmptyText(String str) {
        return str == null || str.isEmpty();
    }

    public static void main(String[] args) {
        String result = CmdHelper.exec("cmd /c netstat -ano | findstr 8080");
        System.out.println("result: " + result);
    }
}
